import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:share_plus/share_plus.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../../../utils/storage_service.dart';
import '../../../data/services/remote_config_service.dart';
import '../../../config/app_constants.dart';
import '../../../config/app_branding.dart';

class AppSettingsController extends GetxController {
  final StorageService _storageService = Get.find<StorageService>();
  final RemoteConfigService _remoteConfigService = Get.find<RemoteConfigService>();

  // 响应式状态
  final RxString appVersion = '1.0.0'.obs;
  final RxBool isDarkMode = false.obs;
  final RxString currentLanguage = '简体中文'.obs;
  final RxBool autoReconnect = true.obs;
  final RxBool isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    _loadSettings();
    _getAppVersion();
  }

  /// 加载设置
  Future<void> _loadSettings() async {
    try {
      // 加载主题设置
      final themeMode = await _storageService.getThemeMode();
      isDarkMode.value = themeMode == 'dark';

      // 加载语言设置
      final language = await _storageService.getLanguage();
      currentLanguage.value = _getLanguageDisplayName(language);

      // 加载自动重连设置
      autoReconnect.value = await _storageService.getBool(AppConstants.keyAutoReconnect) ?? true;
    } catch (e) {
      print('加载设置失败: $e');
    }
  }

  /// 获取应用版本
  Future<void> _getAppVersion() async {
    try {
      final packageInfo = await PackageInfo.fromPlatform();
      appVersion.value = '${packageInfo.version}+${packageInfo.buildNumber}';
    } catch (e) {
      print('获取应用版本失败: $e');
    }
  }

  /// 切换主题
  Future<void> toggleTheme(bool value) async {
    try {
      isDarkMode.value = value;
      final themeMode = value ? 'dark' : 'light';
      await _storageService.setThemeMode(themeMode);
      
      // 更新应用主题
      Get.changeThemeMode(value ? ThemeMode.dark : ThemeMode.light);
      
      _showSuccessMessage('主题已切换');
    } catch (e) {
      _showErrorMessage('切换主题失败');
    }
  }

  /// 更改主题颜色
  Future<void> changeThemeColor(Color color) async {
    try {
      // 这里可以实现主题颜色的保存和应用逻辑
      _showSuccessMessage('主题色已更新');
    } catch (e) {
      _showErrorMessage('更新主题色失败');
    }
  }

  /// 更改语言
  Future<void> changeLanguage(String languageCode) async {
    try {
      await _storageService.setLanguage(languageCode);
      currentLanguage.value = _getLanguageDisplayName(languageCode);
      
      // 更新应用语言
      final locale = _getLocaleFromCode(languageCode);
      Get.updateLocale(locale);
      
      _showSuccessMessage('语言已切换');
    } catch (e) {
      _showErrorMessage('切换语言失败');
    }
  }

  /// 切换自动重连
  Future<void> toggleAutoReconnect(bool value) async {
    try {
      autoReconnect.value = value;
      await _storageService.setBool(AppConstants.keyAutoReconnect, value);
      _showSuccessMessage(value ? '已开启自动重连' : '已关闭自动重连');
    } catch (e) {
      _showErrorMessage('设置自动重连失败');
    }
  }

  /// 清除缓存
  Future<void> clearCache() async {
    try {
      isLoading.value = true;
      
      // 清除各种缓存数据
      await _storageService.clearSearchHistory();
      
      // 这里可以添加更多缓存清理逻辑
      // 比如图片缓存、网络缓存等
      
      await Future.delayed(const Duration(seconds: 1)); // 模拟清理过程
      
      _showSuccessMessage('缓存已清除');
    } catch (e) {
      _showErrorMessage('清除缓存失败');
    } finally {
      isLoading.value = false;
    }
  }

  /// 导出用户数据
  Future<void> exportUserData() async {
    try {
      isLoading.value = true;
      
      // 获取收藏和历史记录
      final favorites = await _storageService.getFavorites();
      final history = await _storageService.getHistory();
      
      // 构建导出数据
      final exportData = {
        'app_name': AppBranding.appName,
        'export_time': DateTime.now().toIso8601String(),
        'version': appVersion.value,
        'favorites': favorites,
        'history': history,
      };
      
      // 转换为JSON字符串
      final jsonString = exportData.toString();
      
      // 分享数据
      await Share.share(
        jsonString,
        subject: '${AppBranding.appName} 数据导出',
      );
      
      _showSuccessMessage('数据导出成功');
    } catch (e) {
      _showErrorMessage('导出数据失败');
    } finally {
      isLoading.value = false;
    }
  }

  /// 运行网络诊断
  Future<void> runNetworkDiagnostics() async {
    try {
      isLoading.value = true;
      
      // 检测网络连接
      final isConnected = await _checkNetworkConnection();
      
      if (isConnected) {
        // 测试远程配置连接
        final configStatus = await _testRemoteConfig();
        
        final message = configStatus 
            ? '网络连接正常，远程配置可访问' 
            : '网络连接正常，但远程配置不可访问';
        
        _showInfoDialog('网络诊断结果', message);
      } else {
        _showInfoDialog('网络诊断结果', '网络连接异常，请检查网络设置');
      }
    } catch (e) {
      _showErrorMessage('网络诊断失败');
    } finally {
      isLoading.value = false;
    }
  }

  /// 检查更新
  Future<void> checkForUpdates() async {
    try {
      isLoading.value = true;
      
      // 这里可以实现检查更新的逻辑
      // 比如从远程服务器获取最新版本信息
      
      await Future.delayed(const Duration(seconds: 2)); // 模拟检查过程
      
      _showInfoDialog('检查更新', '当前已是最新版本');
    } catch (e) {
      _showErrorMessage('检查更新失败');
    } finally {
      isLoading.value = false;
    }
  }

  /// 打开用户协议
  Future<void> openUserAgreement() async {
    try {
      const url = 'https://example.com/user-agreement';
      if (await canLaunchUrl(Uri.parse(url))) {
        await launchUrl(Uri.parse(url));
      } else {
        _showErrorMessage('无法打开用户协议');
      }
    } catch (e) {
      _showErrorMessage('打开用户协议失败');
    }
  }

  /// 打开隐私政策
  Future<void> openPrivacyPolicy() async {
    try {
      const url = 'https://example.com/privacy-policy';
      if (await canLaunchUrl(Uri.parse(url))) {
        await launchUrl(Uri.parse(url));
      } else {
        _showErrorMessage('无法打开隐私政策');
      }
    } catch (e) {
      _showErrorMessage('打开隐私政策失败');
    }
  }

  /// 打开意见反馈
  Future<void> openFeedback() async {
    try {
      // 可以打开邮件客户端或反馈页面
      const email = 'feedback@example.com';
      const subject = '${AppBranding.appName} 意见反馈';
      const body = '请在此处输入您的意见和建议...';
      
      final url = 'mailto:$email?subject=${Uri.encodeComponent(subject)}&body=${Uri.encodeComponent(body)}';
      
      if (await canLaunchUrl(Uri.parse(url))) {
        await launchUrl(Uri.parse(url));
      } else {
        // 如果无法打开邮件客户端，可以复制邮箱地址
        await Clipboard.setData(const ClipboardData(text: email));
        _showSuccessMessage('反馈邮箱已复制到剪贴板');
      }
    } catch (e) {
      _showErrorMessage('打开意见反馈失败');
    }
  }

  /// 检查网络连接
  Future<bool> _checkNetworkConnection() async {
    try {
      // 这里可以实现网络连接检测逻辑
      // 比如ping一个可靠的服务器
      return true; // 暂时返回true
    } catch (e) {
      return false;
    }
  }

  /// 测试远程配置
  Future<bool> _testRemoteConfig() async {
    try {
      await _remoteConfigService.getWikiConfig();
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取语言显示名称
  String _getLanguageDisplayName(String languageCode) {
    switch (languageCode) {
      case 'zh_CN':
        return '简体中文';
      case 'en_US':
        return 'English';
      default:
        return '简体中文';
    }
  }

  /// 从语言代码获取Locale
  Locale _getLocaleFromCode(String languageCode) {
    switch (languageCode) {
      case 'zh_CN':
        return const Locale('zh', 'CN');
      case 'en_US':
        return const Locale('en', 'US');
      default:
        return const Locale('zh', 'CN');
    }
  }

  /// 显示成功消息
  void _showSuccessMessage(String message) {
    Get.snackbar(
      '成功',
      message,
      backgroundColor: Colors.green,
      colorText: Colors.white,
      duration: const Duration(seconds: 2),
    );
  }

  /// 显示错误消息
  void _showErrorMessage(String message) {
    Get.snackbar(
      '错误',
      message,
      backgroundColor: Colors.red,
      colorText: Colors.white,
      duration: const Duration(seconds: 3),
    );
  }

  /// 显示信息对话框
  void _showInfoDialog(String title, String content) {
    Get.dialog(
      AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 重置所有设置
  Future<void> resetAllSettings() async {
    try {
      // 重置主题
      isDarkMode.value = false;
      await _storageService.setThemeMode('light');
      
      // 重置语言
      currentLanguage.value = '简体中文';
      await _storageService.setLanguage('zh_CN');
      
      // 重置其他设置
      autoReconnect.value = true;
      await _storageService.setBool(AppConstants.keyAutoReconnect, true);
      
      _showSuccessMessage('设置已重置');
    } catch (e) {
      _showErrorMessage('重置设置失败');
    }
  }

  /// 获取设置统计信息
  Map<String, dynamic> getSettingsStats() {
    return {
      'theme_mode': isDarkMode.value ? 'dark' : 'light',
      'language': currentLanguage.value,
      'auto_reconnect': autoReconnect.value,
      'app_version': appVersion.value,
    };
  }
}